//editormd图片上传
package controllers

import (
	"fmt"
	"strconv"
	"time"

	// "fmt"
	// "menhu/models"
	"strings"

	beego "github.com/beego/beego/v2/server/web"
)

type ImgController struct {
	beego.Controller
}

type ResEntity struct {
	Success int         `json:"success"`
	Message string      `json:"message"`
	Url     interface{} `json:"url"`
}

var IMG_EXT = []string{"jpg", "jpeg", "png", "bmp", "webp", "JPG", "JPEG", "PNG", "BMP", "WEBP"}

func (this *ImgController) Get() {

}

func (this *ImgController) Post() {

	_, fileHeder, err := this.GetFile("editormd-image-file")

	if err != nil {
		fmt.Println("err:", err)
		res := &ResEntity{0, "服务器错误", nil}
		this.Data["json"] = res
		this.ServeJSON()
	}
	fileName := fileHeder.Filename
	if strings.Index(fileName, ".") <= 0 {
		res := &ResEntity{0, "错误的图片文件!", ""}
		this.Data["json"] = res
		this.ServeJSON()
		return
	}

	strs := strings.Split(fileName, ".")
	ext := strs[len(strs)-1]

	isExtPass := false

	for _, allowedExt := range IMG_EXT {
		if allowedExt == ext {
			isExtPass = true
			break
		}
	}

	if !isExtPass {
		res := &ResEntity{0, "不支持的图片格式!", ""}
		this.Data["json"] = res
		this.ServeJSON()
		return
	}
	uploaddir, _ := beego.AppConfig.String("uploaddir")
	// fmt.Println("uploaddir:", uploaddir)
	fileNewName := strconv.FormatInt(time.Now().Unix(), 10) + "." + ext
	err = this.SaveToFile("editormd-image-file", uploaddir+fileNewName)
	if err != nil {
		fmt.Println(err)
	}
	res := &ResEntity{1, "ok", uploaddir + fileNewName}
	this.Data["json"] = res
	this.ServeJSON()
}
